/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package logica;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author Elias Mendoza
 */
public class RegistroXML {

  List datos;
  Document docum;

  public RegistroXML() {
  }

  public void readXML() {
    try {
      SAXBuilder b = new SAXBuilder();
      docum = b.build("registro.xml");
      datos = docum.getRootElement().getChildren();
    } catch (JDOMException e) {
      System.out.println(e);
    } catch (IOException e) {
      System.out.println(e);
    }
  }

  public void updateInicio(int idHis, int idLec) {
    readXML();
    Element ids = (Element) datos.get(0);
    ids.getAttribute("idHistorial").setValue("" + idHis);
    ids.getAttribute("idLectura").setValue("" + idLec);
    save();
  }

  public void updateIdLectura(String newId) {
    readXML();
    Element ids = (Element) datos.get(0);
    ids.getAttribute("idLectura").setValue(newId);
    save();
  }

  public void updateIdHistorial(String newId) {
    readXML();
    Element ids = (Element) datos.get(0);
    ids.getAttribute("idHistorial").setValue(newId);
    save();
  }

  public int consultaIdHistorial() {
    readXML();
    Element ids = (Element) datos.get(0);
    return Integer.parseInt(ids.getAttribute("idHistorial").getValue());
  }

  public int consultaIdLectura() {
    readXML();
    Element ids = (Element) datos.get(0);
    return Integer.parseInt(ids.getAttribute("idLectura").getValue());
  }

  public void save() {
    XMLOutputter outputter = new XMLOutputter();
    try {
      outputter.setFormat(Format.getCompactFormat());
      FileWriter f = new FileWriter(new File("registro.xml"));
      outputter.output(docum, f);
      f.close();
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}
